package com.usf.jprovider.schema.provider.dao.resultset;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.xml.bind.annotation.XmlElement;

import com.usf.jprovider.object.JObjectNode;
import com.usf.jprovider.object.env.Environment;
import com.usf.jprovider.object.type.JType;
import com.usf.jprovider.schema.provider.AbstractProvider;

public class DAOCallableStatement extends AbstractDAOResultSetSource {

	@XmlElement(name="param") protected AbstractProvider[] params;

	public DAOCallableStatement() {
		super();
		params = new AbstractProvider[]{};
	}

	public AbstractProvider[] getParams() {
		return params;
	}

	@Override
	protected String createUnformated(Environment env, JObjectNode node) throws Exception {
		StringBuffer str = new StringBuffer();
		if(params.length > 0){
			str.append("?");
			for(int i=1; i<params.length; i++)
				str.append(", ?");
		}
		String sql = "{call " + name + "(" + str.toString() + ")}";
		java.sql.CallableStatement call = env.getConnection().prepareCall(sql);
		for(AbstractProvider param : params)
			call.setObject(param.getName(), param.create(env, node).getValue());
		if(!call.execute()) throw new SQLException(""); //TODO correct exception
		ResultSet rs = call.getResultSet();  
		rs.next();
		return rs.getString(1);//TODO selectors
	}

	@Override
	public boolean checkValue(Environment env, JObjectNode node, JType<?> value)
			throws Exception {
		// TODO Auto-generated method stub
		return true;
	}

}
